package jwt.common;


import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jwt.service.JwtService;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;


@Order(-Integer.MAX_VALUE)
@Component
public class LonginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //做接口的前置校验
        boolean checkPreHandle = true;
        //swagger的情况不需要校验token
        if(request.getRequestURI().contains("swagger-resources")){
            checkPreHandle = false;
        }else if(request.getRequestURI().contains("index")){
            //初始化后台接口，不需要校验token
            checkPreHandle = false;
        }

        //如果属于非前置校验的接口类型，则跳过token校验
        if(!checkPreHandle){
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }

        //获取请求头中的令牌
        String token = request.getHeader("token");
        if(token == null || "".equals(token)){
            token = request.getHeader("Authorization");
        }
        System.out.println("当前token为：{}"+ token);
        Map<String, Object> map = new HashMap<>();
        try {
            if(token == null || "".equals(token)){
                throw new Exception();
            }
            JwtService.verifyToken(token);
            return true;
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg", "签名不⼀致");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("msg", "令牌过期");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("msg", "算法不匹配");
        } catch (InvalidClaimException e) {
            e.printStackTrace();
            map.put("msg", "失效的payload");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "token⽆效");
        }
        map.put("status", false);
        //响应到前台: 将map转为json
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}
